<?php

namespace App\Exception\Handler;

use App\Exception\BusinessException;
use App\Log;
use Hyperf\ExceptionHandler\ExceptionHandler;
use Hyperf\HttpMessage\Stream\SwooleStream;
use Psr\Http\Message\ResponseInterface;
use Throwable;

class BusinessExceptionHandler extends ExceptionHandler
{

    /**
     * @param Throwable $throwable
     * @param ResponseInterface $response
     * @return ResponseInterface
     */
    public function handle(Throwable $throwable, ResponseInterface $response): ResponseInterface
    {
        // 判断被捕获到的异常是希望被捕获的异常
        if ($throwable instanceof BusinessException) {
            // 阻止异常冒泡
            $this->stopPropagation();
            Log::get()->error($throwable->getMessage());
            return $response->withStatus($throwable->getCode())->withBody(new SwooleStream(json_encode([
                'code' => 20500,
                'msg' => $throwable->getMessage(),
            ], JSON_UNESCAPED_UNICODE)));
        }
        // 交给下一个异常处理器
        return $response;
        // 或者不做处理直接屏蔽异常
    }

    public function isValid(Throwable $throwable): bool
    {
        return true;
    }
}